/**
 * ==========================================================================
 * ILOVEFREE PHP项目样式迁移JavaScript系统
 * 适配PHP数据结构的标签过滤系统
 * ==========================================================================
 */

class PHPIlovefreeMigration {
    constructor() {
        this.selectedTags = {};
        this.categories = {};
        this.filterDelay = 300;
        this.styleConfig = null;
        this.init();
    }

    /**
     * 初始化迁移系统
     */
    async init() {
        await this.loadStyleConfig();
        this.replaceComponents();
        this.initializeCategories();
        this.bindEvents();
        this.setupAnimations();
        // 在分类初始化完成后应用样式
        this.initializeCategoryStyles();
        console.log('🎨 PHP Ilovefree迁移系统已初始化');
    }

    /**
     * 替换组件属性 - 适配PHP结构
     */
    replaceComponents() {
        console.log('🔧 开始替换组件...');

        // 确保所有nav-grid正确设置
        document.querySelectorAll('.nav-grid').forEach(grid => {
            grid.classList.add('nav-grid');
            console.log('✅ 设置nav-grid:', grid.className);
        });

  
        // 绑定标签点击事件
        document.querySelectorAll('.tag-btn').forEach(btn => {
            if (!btn.hasAttribute('data-click-bound')) {
                const tagId = btn.getAttribute('data-tag-id');
                const categoryId = btn.getAttribute('data-category-id');

                if (categoryId && tagId) {
                    btn.onclick = () => {
                        console.log('🏷️ 点击标签:', categoryId, tagId);
                        this.filterByTag(categoryId, parseInt(tagId));
                    };
                    btn.setAttribute('data-click-bound', 'true');
                    console.log('✅ 绑定标签点击事件:', categoryId, tagId);
                }
            }
        });

        console.log('✅ 组件替换完成');
    }

    /**
     * 初始化分类数据 - 适配PHP结构
     */
    initializeCategories() {
        console.log('📂 初始化分类数据...');

        document.querySelectorAll('.tags-container').forEach(container => {
            const categoryId = container.id.replace('category-', ''); // 移除"category-"前缀

            if (!categoryId) {
                console.warn('⚠️ 找到没有ID的tags-container:', container);
                return;
            }

            const activeBtn = container.querySelector('.tag-btn.active');
            const selectedTag = activeBtn ? parseInt(activeBtn.getAttribute('data-tag-id')) : 0;

            this.categories[categoryId] = {
                id: categoryId,
                selectedTag: selectedTag,
                cards: [],
                tagCounts: {}
            };

            // 查找该分类下的nav-grid
            const navGridId = categoryId.startsWith('category-') ? `nav-grid-${categoryId.replace('category-', '')}` : `nav-grid-${categoryId}`;
            const navGrid = document.getElementById(navGridId);

            if (navGrid) {
                const links = navGrid.querySelectorAll('.nav-link');
                console.log(`📊 分类 ${categoryId} 找到 ${links.length} 个链接`);

                links.forEach(link => {
                    const filters = link.getAttribute('data-tag-filters') || '';
                    const tags = filters.split(',').map(tag => tag.trim()).filter(tag => tag);

                    this.categories[categoryId].cards.push({
                        element: link,
                        tags: tags
                    });

                    // 统计每个标签的数量
                    tags.forEach(tag => {
                        this.categories[categoryId].tagCounts[tag] = (this.categories[categoryId].tagCounts[tag] || 0) + 1;
                    });
                });

                // 计算并更新标签数量
                this.updateTagCounts(categoryId);
            } else {
                console.warn('⚠️ 分类', categoryId, '未找到对应的nav-grid');
            }

            this.selectedTags[categoryId] = selectedTag;
            console.log(`✅ 初始化分类 ${categoryId}: 选中标签${selectedTag}, 卡片${this.categories[categoryId].cards.length}个`);

            // 如果有选中的标签（推荐标签），则立即应用过滤
            if (selectedTag && selectedTag > 0) {
                console.log(`🎯 立即应用推荐标签过滤: ${categoryId} -> ${selectedTag}`);
                this.filterByTag(categoryId, selectedTag);
            }
        });

        console.log('📂 所有分类数据初始化完成:', this.categories);
    }

    /**
     * 更新标签数量显示
     */
    updateTagCounts(categoryId) {
        const category = this.categories[categoryId];
        if (!category) return;

        const containerId = categoryId.startsWith('category-') ? categoryId : `category-${categoryId}`;
        const container = document.getElementById(containerId);
        if (!container) return;

        const tagButtons = container.querySelectorAll('.tag-btn');
        if (tagButtons.length === 0) {
            console.log(`📝 分类 ${categoryId} 没有标签按钮`);
            return;
        }

        tagButtons.forEach(btn => {
            const tagFilter = btn.getAttribute('data-tag-filter');
            const countElement = btn.querySelector('.tag-count');

            if (countElement && tagFilter) {
                if (tagFilter === '推荐') {
                    // "推荐"标签显示包含"推荐"标签的卡片数量
                    const recommendCount = category.cards.filter(card => card.tags.includes('推荐')).length;
                    countElement.textContent = recommendCount;
                } else {
                    // 其他标签显示匹配的卡片数量
                    const count = category.tagCounts[tagFilter] || 0;
                    countElement.textContent = count;
                }
                console.log(`🏷️ 更新标签数量: ${categoryId} - ${tagFilter}: ${countElement.textContent}`);
            }
        });
    }

    /**
     * 按标签过滤 - 适配PHP结构
     */
    filterByTag(categoryId, tagId) {
        const category = this.categories[categoryId];
        if (!category) return;

        this.selectedTags[categoryId] = tagId;

        // 更新标签按钮状态
        this.updateTagButtons(categoryId, tagId);

        // 过滤卡片
        this.filterNavigationItems(categoryId, tagId);

        // 更新分类状态
        category.selectedTag = tagId;

        // 更新当前激活标签的可见数量
        this.updateActiveTagCount(categoryId, tagId);
    }

    /**
     * 更新标签按钮状态
     */
    updateTagButtons(categoryId, activeTagId) {
        const containerId = categoryId.startsWith('category-') ? categoryId : `category-${categoryId}`;
        const container = document.getElementById(containerId);
        if (!container) return;

        container.querySelectorAll('.tag-btn').forEach(btn => {
            const btnTagId = parseInt(btn.getAttribute('data-tag-id'));
            if (btnTagId === activeTagId) {
                btn.classList.add('active');
            } else {
                btn.classList.remove('active');
            }
        });
    }

    /**
     * 更新当前激活标签的可见数量
     */
    updateActiveTagCount(categoryId, tagId) {
        const category = this.categories[categoryId];
        if (!category) return;

        const containerId = categoryId.startsWith('category-') ? categoryId : `category-${categoryId}`;
        const container = document.getElementById(containerId);
        if (!container) return;

        const activeBtn = container.querySelector(`.tag-btn[data-tag-id="${tagId}"]`);
        const countElement = activeBtn?.querySelector('.tag-count');

        if (!countElement) return;

        let visibleCount = 0;

        const isRecommendTag = activeBtn?.getAttribute('data-tag-filter') === '推荐';

        if (isRecommendTag) {
            // "推荐"标签显示匹配的导航数量
            visibleCount = category.cards.filter(card => {
                const isVisible = card.element.style.display !== 'none' && !card.element.classList.contains('hidden');
                return isVisible && card.tags.includes('推荐');
            }).length;
        } else {
            // 其他标签显示当前过滤后的可见数量
            const tagFilter = activeBtn?.getAttribute('data-tag-filter');
            if (tagFilter) {
                visibleCount = category.cards.filter(card => {
                    const isVisible = card.element.style.display !== 'none' && !card.element.classList.contains('hidden');
                    const matchesTag = card.tags.includes(tagFilter);
                    return isVisible && matchesTag;
                }).length;
            }
        }

        countElement.textContent = visibleCount;
        console.log(`🔢 更新激活标签数量: ${categoryId} - 标签${tagId}: ${visibleCount}`);
    }

    /**
     * 过滤导航卡片
     */
    filterNavigationItems(categoryId, tagId) {
        const category = this.categories[categoryId];
        if (!category) return;

        let visibleCount = 0;

        category.cards.forEach((card, index) => {
            const containerId = categoryId.startsWith('category-') ? categoryId : `category-${categoryId}`;
            const container = document.getElementById(containerId);
            const activeBtn = container?.querySelector(`.tag-btn[data-tag-id="${tagId}"]`);
            const isRecommendTag = activeBtn?.getAttribute('data-tag-filter') === '推荐';

            const shouldShow = isRecommendTag ?
                card.tags.includes('推荐') :
                this.matchesTag(card.tags, tagId, categoryId);

            if (shouldShow) {
                this.showCard(card.element, index);
                visibleCount++;
            } else {
                this.hideCard(card.element);
            }
        });

        // 检查空状态
        this.checkEmptyState(categoryId, visibleCount);

        // 记录过滤操作
        this.logFilterAction(categoryId, tagId, visibleCount);
    }

    /**
     * 检查卡片是否匹配标签
     */
    matchesTag(cardTags, tagId, categoryId) {
        const containerId = categoryId.startsWith('category-') ? categoryId : `category-${categoryId}`;
        const container = document.getElementById(containerId);
        const activeBtn = container?.querySelector(`.tag-btn[data-tag-id="${tagId}"]`);
        const filterText = activeBtn?.getAttribute('data-tag-filter');

        return filterText && cardTags.includes(filterText);
    }

    /**
     * 显示卡片
     */
    showCard(element, index) {
        element.style.display = 'block';
        element.classList.remove('hidden', 'filtering');
        element.style.opacity = '1';
        element.style.transform = 'scale(1)';
    }

    /**
     * 隐藏卡片
     */
    hideCard(element) {
        element.style.opacity = '0';
        element.style.transform = 'scale(0.8)';
        element.classList.add('hidden');
        element.style.display = 'none';
        element.classList.remove('filtering');
    }

    /**
     * 检查空状态
     */
    checkEmptyState(categoryId, visibleCount) {
        const category = this.categories[categoryId];
        const categoryIdStr = String(categoryId);
        const gridElementId = categoryIdStr.startsWith('category-') ? `nav-grid-${categoryIdStr.replace('category-', '')}` : `nav-grid-${categoryIdStr}`;
        const gridElement = document.getElementById(gridElementId);

        if (!gridElement) return;

        // 移除现有空状态提示
        const existingEmpty = gridElement.querySelector('.empty-state');
        if (existingEmpty) {
            existingEmpty.remove();
        }

        // 如果没有可见卡片，显示空状态
        if (visibleCount === 0) {
            const emptyState = document.createElement('div');
            emptyState.className = 'empty-state';
            emptyState.innerHTML = `
                <div style="text-align: center; padding: 3rem; color: var(--text-muted);">
                    <i class="fas fa-search" style="font-size: 3rem; margin-bottom: 1rem; opacity: 0.5;"></i>
                    <p>没有找到匹配的资源</p>
                    <p style="font-size: 0.875rem; margin-top: 0.5rem;">试试选择其他标签</p>
                </div>
            `;
            gridElement.appendChild(emptyState);
        }
    }

    /**
     * 记录过滤操作
     */
    logFilterAction(categoryId, tagId, visibleCount) {
        console.log(`🔍 过滤操作: ${categoryId} -> 标签${tagId}, 显示${visibleCount}个结果`);
    }

    /**
     * 绑定事件监听器
     */
    bindEvents() {
        // 标签点击事件已通过onclick绑定

        // 响应式布局监听
        window.addEventListener('resize', this.debounce(() => {
            this.handleResponsiveLayout();
        }, 250));
    }

    /**
     * 设置动画效果
     */
    setupAnimations() {
        // 为链接添加渐进式动画
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.style.animationPlayState = 'running';
                }
            });
        }, { threshold: 0.1 });

        document.querySelectorAll('.nav-link').forEach(link => {
            link.style.animationPlayState = 'paused';
            observer.observe(link);
        });
    }

    /**
     * 处理响应式布局
     */
    handleResponsiveLayout() {
        const width = window.innerWidth;

        // 根据屏幕宽度调整网格布局
        document.querySelectorAll('.nav-grid').forEach(grid => {
            if (width < 480) {
                grid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(140px, 1fr))';
            } else if (width < 768) {
                grid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(150px, 1fr))';
            } else if (width < 1024) {
                grid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(160px, 1fr))';
            } else {
                grid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(180px, 1fr))';
            }
        });
    }

    /**
     * 防抖函数
     */
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    /**
     * 获取当前过滤状态
     */
    getFilterState() {
        return { ...this.selectedTags };
    }

    /**
     * 重置所有过滤
     */
    resetFilters() {
        Object.keys(this.selectedTags).forEach(categoryId => {
            this.filterByTag(categoryId, 0);
        });
    }

    /**
     * 加载样式配置
     */
    async loadStyleConfig() {
        try {
            const response = await fetch('./styles-config.json');
            if (response.ok) {
                this.styleConfig = await response.json();
                console.log('🎨 样式配置加载成功:', this.styleConfig);
            } else {
                console.warn('⚠️ 样式配置文件加载失败，使用默认配置');
                this.styleConfig = {
                    styles: {
                        STYLE_1: { name: "样式一", css_class: "nav-style-1" },
                        STYLE_2: { name: "样式二", css_class: "nav-style-2" },
                        STYLE_3: { name: "样式三", css_class: "nav-style-3" },
                        STYLE_4: { name: "样式四", css_class: "nav-style-4" },
                        STYLE_5: { name: "样式五", css_class: "nav-style-5" }
                    },
                    default_style: "STYLE_1"
                };
            }
        } catch (error) {
            console.error('❌ 加载样式配置时发生错误:', error);
            this.styleConfig = {
                styles: {
                    STYLE_1: { name: "样式一", css_class: "nav-style-1" },
                    STYLE_2: { name: "样式二", css_class: "nav-style-2" },
                    STYLE_3: { name: "样式三", css_class: "nav-style-3" },
                    STYLE_4: { name: "样式四", css_class: "nav-style-4" },
                    STYLE_5: { name: "样式五", css_class: "nav-style-5" }
                },
                default_style: "STYLE_1"
            };
        }
    }

    /**
     * 应用分类样式
     * 注意：由于样式现在由PHP服务端直接渲染，此方法已被简化
     */
    applyCategoryStyle(categoryId, displayStyle) {
        // 样式现在由PHP服务端直接渲染到HTML中，无需JavaScript动态应用
        // 保留此方法以确保兼容性，但不再执行动态样式切换
        console.log(`🎨 样式由服务端渲染: ${categoryId} (${displayStyle}) - 无需动态应用`);
    }

    /**
     * 获取分类的显示样式
     */
    getCategoryDisplayStyle(categoryId) {
        // 从data属性中获取样式信息
        const categoryIdStr = String(categoryId);
        const categorySection = document.querySelector(`[data-category-id="${categoryIdStr}"]`) ||
                              document.querySelector(`#category-${categoryIdStr}`) ||
                              document.querySelector(`[data-category="${categoryIdStr}"]`);

        if (categorySection) {
            const displayStyle = categorySection.getAttribute('data-display-style') ||
                               categorySection.getAttribute('data-category-style') ||
                               this.styleConfig?.default_style || 'STYLE_1';
            return displayStyle;
        }

        console.warn(`⚠️ 无法获取分类 ${categoryId} 的显示样式，使用默认样式`);
        return this.styleConfig?.default_style || 'STYLE_1';
    }

    /**
     * 初始化所有分类的样式
     * 注意：由于样式现在由PHP服务端直接渲染，此方法已被简化
     */
    initializeCategoryStyles() {
        // 样式现在由PHP服务端直接渲染到HTML中，无需JavaScript动态应用
        // 保留此方法以确保兼容性，但不再执行动态样式切换
        console.log('🎨 样式由服务端渲染，跳过JavaScript动态样式应用');
    }
}

/**
 * 初始化PHP迁移系统
 */
document.addEventListener('DOMContentLoaded', () => {
    // 初始化迁移系统
    window.phpIlovefreeMigration = new PHPIlovefreeMigration();

    // 添加全局方法供外部调用
    window.filterByTag = (categoryId, tagId) => {
        window.phpIlovefreeMigration.filterByTag(categoryId, tagId);
    };

    console.log('🎉 PHP Ilovefree迁移系统加载完成');
});

// 导出模块（如果使用模块系统）
if (typeof module !== 'undefined' && module.exports) {
    module.exports = PHPIlovefreeMigration;
}